﻿namespace ScrumSprintMonitor.Modules.WorkItemMonitor.Controls
{
	#region #using Directives

	using System;
	using System.ComponentModel;
	using System.Windows;
	using System.Windows.Controls;
	using System.Windows.Media;
	using System.Windows.Media.Animation;
	using System.Windows.Threading;

	using UI.Wpf.ViewModels;

	#endregion

	/// <summary>
	/// Interaction logic for SprintWarningBorder.xaml
	/// </summary>
	public partial class SprintWarningBorder : Border
	{
		private ITeamMembersListViewModel teamMembersListViewModel;

		public SprintWarningBorder()
		{
			InitializeComponent();
		}

		private void OnDataContextChanged()
		{
			if (this.teamMembersListViewModel != DataContext)
			{
				if (this.teamMembersListViewModel != null)
				{
					this.teamMembersListViewModel.PropertyChanged -= teamMembersListViewModel_PropertyChanged;
					this.teamMembersListViewModel = null;
				}

				this.teamMembersListViewModel = (ITeamMembersListViewModel) DataContext;
				if (this.teamMembersListViewModel != null)
				{
					this.teamMembersListViewModel.PropertyChanged += teamMembersListViewModel_PropertyChanged;
				}
			}
		}

		private void Border_Loaded(object sender, RoutedEventArgs e)
		{
			OnDataContextChanged();

			// Remove any databinding
			if (Background == null)
			{
				Background = (this.teamMembersListViewModel != null
				              	? new SolidColorBrush(this.teamMembersListViewModel.SprintWarningBackgroundColor)
				              	: Brushes.Transparent);
			}
			else
			{
				Background = Background.CloneCurrentValue();
			}
		}

		private void Border_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
		{
			OnDataContextChanged();
		}

		private void teamMembersListViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "SprintWarningBackgroundColor":
					Dispatcher.BeginInvoke(new Action<Border, Color>(BeginAnimation), DispatcherPriority.Background, this,
					                       this.teamMembersListViewModel.SprintWarningBackgroundColor);
					break;
			}
		}

		private static void BeginAnimation(Border border, Color targetColor)
		{
			// Prevent problems with a frozen value
			border.Background = border.Background.CloneCurrentValue();

			border.Background.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation(targetColor, new Duration(TimeSpan.FromSeconds(5.0))));
		}
	}
}